package top.wettis.chat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.wettis.chat.constant.ResultCode;
import top.wettis.chat.constant.ResultType;
import top.wettis.chat.pojo.DO.Expert;
import top.wettis.chat.pojo.VO.Result;
import top.wettis.chat.service.IExpertService;
import top.wettis.chat.service.impl.IExpertServiceImpl;

import java.util.List;

@RestController
@CrossOrigin(origins = "*")
@Slf4j
@RequestMapping("/chat/expert")
public class ExpertController {
    @Autowired
    private IExpertService expertService;


    /**
     * 查询列表
     */
    @GetMapping("/list")
    @ResponseBody
    private Result<Object> list(String expertName) {

        List<Expert> list = expertService.expertPage(expertName);
        if (list == null) {
            return Result.failInfo(ResultType.GET, null);
        }
        return Result.successInfo(ResultType.GET, list);
    }

    /**
     * 保存和修改
     */
    @PostMapping("/save_update")
    public Result<Object> Save(@RequestBody Expert expert) {
        log.info(expert.getExpertName());
        if (expert.getExpertId() == null) {
            LambdaQueryWrapper<Expert> expertLambdaQueryWrapper = new LambdaQueryWrapper<>();
            expertLambdaQueryWrapper.eq(Expert::getExpertName, expert.getExpertName());
            long count = expertService.count(expertLambdaQueryWrapper);
            boolean save = false;
            if (count == 0) {
                save = expertService.save(expert);
            }
            if (save) {
                return Result.successInfo(ResultType.SAVE, "添加成功");
            } else {
                return Result.customInfo(500 , "该专家已存在", null );
            }
        } else {
            boolean update = expertService.updateById(expert);
            if (update) {
                return Result.successInfo(ResultType.UPDATE, "修改成功");
            } else {
                return Result.customInfo(500 , "修改失败或该专家不存在", null);
            }
        }
    }

    /**
     * 删除
     */

    @DeleteMapping("/delete/{id}")
    public Result<Object> Delete(@PathVariable Integer id) {
        expertService.removeById(id);
        return Result.successInfo(ResultType.DELETE, ResultCode.DELETE_OK);
    }

    /**
     * 查询id
     */
    @GetMapping("/select/{id}")
    public Result<Object> select(@PathVariable Integer id) {
        Expert expert = expertService.getById(id);
        if (expert != null) {
            return Result.successInfo(ResultType.GET, ResultCode.GET_OK);
        } else {
            return Result.successInfo(ResultType.GET, ResultCode.GET_ERR);
        }
    }



}
